/*
 * time_udp_client.c
 * 
 */


#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <memory.h>
#include <arpa/inet.h>

#define NAME_SIZE 20
#define CONT_SIZE 128

enum Chat_Opt{
	ADD,
	DEL,
	CHAT,
	ONLINE
};

typedef struct Chat_pack{
//head
	char head[5];
//data
	enum Chat_Opt chat_opt;
	char sender[NAME_SIZE];
	char recv[NAME_SIZE];
	int checknum;
	char content[CONT_SIZE];
}chat_t;

//判断输入是否为域名
int is_host(struct hostent* host,char* name)
{
	if(!strcmp(host->h_name,name))return 1;
	int i=0;
	while(host->h_aliases[i]!=NULL){
		if(!strcmp(host->h_aliases[i],name))return 1;
		++i;
	}
	return 0;
}

unsigned int get_ip_by_name(char *name)
{
	unsigned int ip = 0;
	struct hostent *host;
	while((host = gethostent())!=NULL){
		if(is_host(host,name)){ //判断传进来的域名是否在/etc/hosts里面
			memcpy(&ip, host->h_addr_list[0], 4);
			break;
		}
	}
	endhostent();
	return ip;
}

int main(int argc, char **argv)
{
	if(argc<3){
		printf("usage: %s ip port\n",argv[0]);
		exit(1);
	}
	
	/*步骤1：创建socket*/
	int sockfd = socket(AF_INET, SOCK_DGRAM,0);
	if(sockfd<0){
		perror("socket error");
		exit(1);
	}
	
	/*步骤2：调用recvfrom和sendto函数
	 * 和服务器端双向通讯
	 * */
	 struct sockaddr_in serveraddr;
	 memset(&serveraddr,0,sizeof(serveraddr));
	 serveraddr.sin_family = AF_INET;
	 serveraddr.sin_port = htons(atoi(argv[2]));//port
	 //inet_pton(AF_INET,argv[1],
					//&serveraddr.sin_addr.s_addr);//ip
					
	/*使用域名解析*/
	unsigned int ip = get_ip_by_name(argv[1]);
	if(ip!=0){
		serveraddr.sin_addr.s_addr = ip;
	}else{ //如果根据域名无法找到ip
		inet_pton(AF_INET,argv[1],&serveraddr.sin_addr.s_addr);
	}
	
	if(connect(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr))<0){
		perror("connect error");
		exit(1);
	}
	
	char buffer[512] ;
	memset(buffer,0,sizeof(buffer));
	chat_t chat={"chat",CHAT,"sender","receiver",1,"hello"};
	memcpy(buffer,&chat,sizeof(chat_t));
	//向服务器发送数据报文
	if(sendto(sockfd,buffer,sizeof(buffer),0,
		(struct sockaddr*)&serveraddr,sizeof(serveraddr))<0){
			perror("sendto error");
			exit(1);
	}
	//else{
		///*成功发送后，开始接收服务器发送的数据报文(因为之前已经知道服务器端的信息，所以直接用recv函数)
		 //* */
		//memset(buffer,0,sizeof(buffer));
		//if(recv(sockfd,buffer,sizeof(buffer),0)<0){
			//perror("recv error");
			//exit(1);
		//}
		//else{
			//printf("%s",buffer);
		//}
	//}	
	close(sockfd);
	
	
	return 0;
}

